#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2016-10-19 11:48:05
# @Author  : Your Name (you@example.org)
# @Link    : http://example.org
# @Version : $Id$

import os
import conf,db
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

class Cmdb(object):
    #机房添加
    def room_add(self,info):
        if not str(info).strip():
            result = {
                'code': 2009,
                'message': '机房名称不能为空'
            }
            return result
        query = 'INSERT INTO room(info) values("{info}")'.format(info=info)
        try:
            resu = db.db_insert_on(query)
            if resu == 1:
                result = {
                    'code': 0000,
                    'message': '添加机房:{0} 成功!'.format(info) }
            else:
                result = {
                    'code': 2006,
                    'message': '插入失败: '+resu
                }
            return result
        except Exception, e:
            result = {
                'code': 2009,
                'message': '错误: '+str(e)
            }
            return result
    #机房修改
    def room_edit(self,id,info):
        query = 'UPDATE room SET info="{info}" WHERE id="{id}"'.format(info=info,id=id)
        try:
            resu = db.db_update_on(query)
            if resu in (0,1): #如果条件不成立，也返回0，其实没有修改
                result = {
                    'code': 0000,
                    'message': '修改成功'
                }
            else:
                result = {
                    'code': 2010,
                    'message': conf._code.get(2010,'修改失败') +resu
                }
            return result
        except Exception, e:
            result = {
                'code': 2009,
                'message': '错误: '+str(e) }
            return result
    #机房删除
    def room_del(self,id):
        query = 'DELETE FROM room where id="{id}"'.format(id=id)
        try:
            resu = db.db_delete_on(query)
            if resu in (0,1):
                result = {
                    'code': 0000,
                    'message': '删除成功' }
            else:
                result = {
                    'code': 2012,
                    'message': conf._code.get(2012,'删除失败') +resu }
            return result
        except Exception, e:
            result = {
                'code': 2009,
                'message': '错误: '+str(e) }
            return result
    #机房列表
    def room_list(self):
        query = 'SELECT * FROM room ORDER BY id'
        try:
            datas = db.db_select_all(query)
            result = {
                'code': 0000,
                'message': '查询成功',
                'data': datas
            }
            return result
        except Exception, e:
            result = {
                'code': 2009,
                'message': '错误: '+str(e)
            }
            return result

    #机柜添加
    def cabinet_add(self,info):
        if not str(info).strip():
            result = {
                'code': 2009,
                'message': '机柜名称不能为空'
            }
            return result
        query = 'INSERT INTO cabinet(info) values("{info}")'.format(info=info)
        try:
            resu = db.db_insert_on(query)
            if resu == 1:
                result = {
                    'code': 0000,
                    'message': '添加机柜:{0} 成功!'.format(info) }
            else:
                result = {
                    'code': 2006,
                    'message': '插入失败: '+resu
                }
            return result
        except Exception, e:
            result = {
                'code': 2009,
                'message': '错误: '+str(e)
            }
            return result

    #机柜修改
    def cabinet_edit(self,id,info):
        query = 'UPDATE cabinet SET info="{info}" WHERE id="{id}"'.format(info=info,id=id)
        try:
            resu = db.db_update_on(query)
            if resu in (0,1): #如果条件不成立，也返回0，其实没有修改
                result = {
                    'code': 0000,
                    'message': '修改成功' }
            else:
                result = {
                    'code': 2010,
                    'message': conf._code.get(2010,'修改失败') +resu  }
            return result
        except Exception, e:
            result = {
                'code': 2009,
                'message': '错误: '+str(e) }
            return result
    #机柜删除
    def cabinet_del(self,id):
        query = 'DELETE FROM cabinet where id="{id}"'.format(id=id)
        try:
            resu = db.db_delete_on(query)
            if resu in (0,1):
                result = {
                    'code': 0000,
                    'message': '删除成功' }
            else:
                result = {
                    'code': 2012,
                    'message': conf._code.get(2012,'删除失败') +resu }
            return result
        except Exception, e:
            result = {
                'code': 2009,
                'message': '错误: '+str(e) }
            return result
    #机柜列表
    def cabinet_list(self):
        query = 'SELECT * FROM cabinet ORDER BY id'
        try:
            datas = db.db_select_all(query)
            result = {
                'code': 0000,
                'message': '查询成功',
                'data': datas
            }
            return result
        except Exception, e:
            result = {
                'code': 2009,
                'message': '错误: '+str(e)
            }
            return result

    #主机添加
    def host_add(self,application,ip,port,username,password,
				cpu,mem,disk,room_id,cabinet_id,location):
        query = '''
			INSERT INTO cmdb(application,ip,port,username,
				password,cpu,mem,disk,room_id,cabinet_id,location)
			VALUES ('{application}','{ip}','{port}','{username}',
			  '{password}','{cpu}',	'{mem}','{disk}','{room_id}','{cabinet_id}',
			  '{location}')'''.format(application=application,ip=ip,port=port,
			    username=username,password=password,cpu=cpu,mem=mem,
                disk=disk,room_id=room_id,cabinet_id=cabinet_id,
                location=location)
        try:
            resu = db.db_insert_on(query)
            if resu == 1:
                result = {
                    'code': 0000,
                    'message': '添加主机成功' }
            else:
                result = {
                    'code': 2006,
                    'message': '插入失败: '+resu
                }
            return result
        except Exception, e:
            result = {
                'code': 2009,
                'message': '错误: '+str(e)
            }
            return result
    #主机修改
    def host_edit(self,id,application,ip,port,username,password,
				cpu,mem,disk,room_id,cabinet_id,location):
        query = '''
			UPDATE cmdb SET application='{application}',
				ip='{ip}',
				port='{port}',
				username='{username}',
				password='{password}',
				cpu='{cpu}',
				mem='{mem}',
				disk='{disk}',
				room_id='{room_id}',
				cabinet_id='{cabinet_id}',
				location='{location}'
			WHERE
				id={id}
		'''.format(id=id,application=application,ip=ip,port=port,
				   username=username,password=password,cpu=cpu,
				   mem=mem,disk=disk,room_id=room_id,
				   cabinet_id=cabinet_id,location=location)
        try:
            resu = db.db_update_on(query)
            if resu in (0,1): #如果条件不成立，也返回0，其实没有修改
                result = {
                    'code': 0000,
                    'message': '修改成功' }
            else:
                result = {
                    'code': 2010,
                    'message': conf._code.get(2010,'修改失败') +resu  }
            return result
        except Exception, e:
            result = {
                'code': 2009,
                'message': '错误: '+str(e) }
            return result

    #主机删除
    def host_del(self,id):
        query = 'DELETE FROM cmdb where id="{id}"'.format(id=id)
        try:
            resu = db.db_delete_on(query)
            if resu in (0,1):
                result = {
                    'code': 0000,
                    'message': '删除成功' }
            else:
                result = {
                    'code': 2012,
                    'message': conf._code.get(2012,'删除失败') +resu }
            return result
        except Exception, e:
            result = {
                'code': 2009,
                'message': '错误: '+str(e) }
            return result

    #主机列表
    def host_list(self):
        query = '''
            SELECT cmdb.id,application,ip,cpu,mem,disk,room.info AS room_info,
			        cabinet.info AS cabinet_info,location
	          FROM cmdb,room,	cabinet
		        WHERE
			      cmdb.room_id = room.id AND cmdb.cabinet_id = cabinet.id
			      ORDER BY cmdb.id
            '''
        try:
            datas = db.db_select_all(query)
            result = {
                'code': 0000,
                'message': '查询成功',
                'data': datas
            }
            return result
        except Exception, e:
            result = {
                'code': 2009,
                'message': '错误: '+str(e)
            }
            return result

if __name__ == '__main__':
    c = Cmdb()
    # r = c.room_del('80')
    # print r['code'],r['message']
    # r = c.room_list()
    # print r['code'],r['message'],r['data']
    # for i,j in r['data']:
    #     print i,j
    r = c.host_list()
    print r['code'],r['message']
    print r['data']